package com.edu.controller;

import com.edu.bean.Like;
import com.edu.bean.User;
import com.edu.service.LikeService;
import com.edu.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Author 75099637@qq.com
 * @PackageName SpringAndMybatis
 * @Package com.edu.controller
 * @Date 2023/11/9 10:35
 * @Version 1.0
 */
@Controller
@RequestMapping(value = "/users")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private LikeService likeService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public Object login(String username, String password, HttpSession session) {
        ModelAndView mv = new ModelAndView();
        User user = userService.getUserByUserName(username);
        if (session.getAttribute("loginUser") != null) {
            mv.setViewName("/user/login");
            mv.addObject("errorCode", "0");
        } else {
            Map<String, Object> map = userService.login(username, password);
            if (map.get("loginUser") != null) {
                mv.setViewName("forward:/books/selectBookAll?pageNum=1");
                session.setAttribute("loginUser", map.get("loginUser"));
            } else if (!user.getPassword().equals(password)) {
                mv.setViewName("/user/login");
                mv.addObject("err", "密码错误：" + password);
            } else {
                mv.setViewName("/user/login");
                mv.addObject("errorCode", map.get("msg"));
            }
        }
        return mv;
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Object register(User user, @RequestParam(name = "likeType", required = false) String[] likeType) {
        ModelAndView mv = new ModelAndView();
        int count = userService.register(user);
        User user1 = userService.getUserByUserName(user.getUsername());
        for (String likeList : likeType) {
            likeService.insertLike(new Like(likeList, user1.getUserId()));
        }
        if (count == -1) {
            mv.setViewName("/user/register");
            mv.addObject("msg", "-1");
        } else if (count == 1) {
            mv.setViewName("/user/login");
            mv.addObject("msg", "1");
        }
        return mv;
    }
}
